import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';

import {
    Button,
    DatePicker,
    Form,
    Input,
    Modal,
    Radio,
    Tag,
    Select,
    InputNumber,
    message,
    Row,
    Col,
    Tree,
} from 'antd';
import { modalLayoutLg, modalLayoutSm } from '@/config/layout';
import { request, useModel } from 'umi';
import './index.less'
import apilist from '@/pages/sysman/index/apilist';
import { handleOrgTreeList } from '@/utils'
const SelectComp = (props: any, refs: any) => {
    const { initialState, setInitialState } = useModel('@@initialState');
    const { currentUser } = initialState;
    const [code, setCode] = useState('');
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [treeData, settreedata] = useState([]);
    const [value, setvalue] = useState('')
    const [searchStr, setsearchStr] = useState('')
    const [selectObj, setselectObj] = useState({})
    const [orglist, setorglist] = useState([]);
    const [org_no, setorg_no] = useState('');
    const [searchvalue, setsearchvalue] = useState('');
    //显示弹窗
    const showModal = () => {
        setIsModalVisible(true);
    };

    //取消
    const handleCancel = () => {
        setIsModalVisible(false);
        setCode('');
        setsearchStr('')
        props.callback && props.callback();
    };
    //确定
    const handleOk = () => {
        if (value == '') {
            message.error('必须选择一个')
        } else {
            props.onOk({
                ...selectObj,
            })
            handleCancel();
            // request(`/data/dynamic/query`, {
            //     method: 'POST',
            //     headers: {
            //         'Content-Type': 'application/json',
            //     },
            //     data: {
            //         apiID: 'GZW_ORG_03',
            //         apiParam: {
            //             hyp_org_no: selectObj.id,
            //             hyp_org_name: selectObj.name,
            //             sno: 1,
            //             updater: currentUser.user_name,
            //             rls_id: code,
            //         }

            //     }
            // }).then((res) => {
            //     console.log(res)
            //     message.success(res?.meta?.msg);
            //     handleCancel();
            // })
        }
    };
    useImperativeHandle(refs, () => ({
        init: (id: any, record: any) => {
            setCode(id);

            showModal();
            // setfileList([]);
        },
    }));

    const getdata = async () => {
        const responsePermission: any = await request(`/data/dynamic/query`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            data: {
                "apiID": "GZW_USER_PERMISSION_01",
                "apiParam": {
                    'orderBy': 'user_id',
                    // "paging": { "pageSize": params.pageSize, "pageNum": params.current },
                    "where": [
                        {
                            'feild': "user_id",
                            'value': currentUser.user_id
                        }
                    ]
                }
            }
        });
        let dataPermission = responsePermission?.data?.data || [];
        let PermissionObj = {};
        dataPermission.map((e) => {

            PermissionObj[e.gzw_org_no] = true
        })
        const response: any = await request('/data/financial/report/cur', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            data: {

            },
        });
        let data = response?.data || [];
        data.map((e, i) => {
            if (PermissionObj[e.gzw_org_no]) {
                data[i]['disabled'] = false;
            } else {
                data[i]['disabled'] = true
            }
        })
        setorglist(data);
        let datas = handleOrgTreeList(data)
        console.log(datas);
        let expandedKeysn = [];
        // 递归datas 如果有childrens 那么把gzw_org_no添加到expandedKeysn
        const handleexpandedKeysn = (list) => {
            list.map((e) => {
                if (e.children && e.children.length > 0) {
                    expandedKeysn.push(e.gzw_org_no);
                    handleexpandedKeysn(e.children)
                }
            })
        }
        handleexpandedKeysn(datas)
        // setexpandedKeys(expandedKeysn)
        console.log(expandedKeysn);
        console.log(datas);
        settreedata(datas);
    };
    useEffect(() => {
        getdata()
    }, [])
    const onChange = (e) => {
        setsearchStr(e.target.value)
    }
    let reportstatus = { '-1': '未创建', 0: '草稿', 1: '本部表已上传', 2: '汇总表已上传', 3: '全部已上传' };
    let reportstatuscolor = { '-1': '#ccc', 0: 'gray', 1: 'orange', 2: 'green', 3: 'blue' };
    return (
        <Modal
            title={'选择'}
            visible={isModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
            centered
            width={1000}
            maskClosable={false}
            bodyStyle={{
                maxHeight: window.innerHeight - 150,
                overflowY: 'auto',
            }}
        >
            {/* <Input.Search value={searchStr} style={{ marginBottom: 8 }} placeholder="搜索" onChange={onChange} /> */}
            {
                treeData.length > 0 && <div>
                    <Input.Search value={searchvalue} onChange={(e) => { setsearchvalue(e.target.value) }} />
                    <div style={{ height: '10px' }}></div>
                    {
                        searchvalue ? <div className='searchWrap'>
                            {
                                orglist.map((node, i) => {
                                    if (node.gzw_org_name.indexOf(searchvalue) > -1) {
                                        let has_report = node.has_report
                                        return <div className={'reporttreeNode ' + (node.gzw_org_no == value ? 'active' : '')} key={i} onClick={() => {
                                            setvalue(node.gzw_org_no)
                                            setselectObj({
                                                id: node.gzw_org_no,
                                                name: node.gzw_org_name
                                            })
                                        }}>
                                            <div className='reporttreeNodeName'><span className={node.is_single ? 'single' : 'merge'}>{node.is_single ? '单' : '合'}</span>{node.gzw_org_name}</div>
                                        </div>
                                    }
                                })
                            }
                        </div> : <Tree
                            treeData={treeData}
                            defaultCheckedKeys={[value]}
                            selectedKeys={[value]}
                            style={{ maxHeight: window.innerHeight - 250, overflowY: 'auto' }}
                            defaultExpandAll
                            fieldNames={{ title: 'gzw_org_name', key: 'gzw_org_no' }}
                            onSelect={(selectedKeys, e) => {
                                setvalue(selectedKeys[0])
                                console.log(e);
                                setselectObj({
                                    id: e.node.gzw_org_no,
                                    name: e.node.gzw_org_name
                                })
                            }}
                            blockNode
                            titleRender={(node) => {
                                let has_report = node.has_report
                                return <div className='reporttreeNode'>
                                    <div className='reporttreeNodeName'><span className={node.is_single ? 'single' : 'merge'}>{node.is_single ? '单' : '合'}</span>{node.gzw_org_name}</div>
                                </div>
                            }}
                        // titleRender={(node) => {
                        //     const issh = searchStr == '' ? false : (node.gzw_org_name.indexOf(searchStr) !== -1);
                        //     return <div className={issh ? 'indexHblTreeNode' : ''}>{node.gzw_org_name}</div>
                        // }}
                        />
                    }

                </div>




            }
        </Modal>
    );
};
const SelectCom = forwardRef(SelectComp);
export default SelectCom;
